package com.zl.cms.controller;

import com.zl.basic.CommonUtil.EnumUtil;
import com.zl.cms.auth.AuthClass;
import com.zl.cms.auth.AuthMethod;
import com.zl.cms.dto.AjaxObj;
import com.zl.cms.dto.TreeDto;
import com.zl.cms.model.Channel;
import com.zl.cms.model.ChannelTree;
import com.zl.cms.model.ChannelType;
import com.zl.cms.service.IChannelService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-2-2 Time: 下午4:40
 */
@Controller
@RequestMapping("/admin/channel")
@AuthClass
public class ChannelController {

  private IChannelService channelService;

  public IChannelService getChannelService() {
    return channelService;
  }

  @Inject
  public void setChannelService(IChannelService channelService) {
    this.channelService = channelService;
  }

  // 用来显示子栏目在表格里
  @RequestMapping("/channels/{pid}")
  public String listChild(@PathVariable Integer pid, @RequestParam(value = "refresh",required = false) Integer refresh, Model model) {
	  if(refresh == null) {
		  model.addAttribute("refresh", 0);
	  }else{

		  model.addAttribute("refresh", 1);
	  }
	  Channel pc = null;
    // 第一次打开显示树的页面显示网站系统栏目。此时网站系统栏目的id是0，需要手动构造添加一个栏目pc,这个pc是树根
    // 将pid==null,因为数据库中以树根为父节点的栏目的pid是null,第一次显示所有已树根为父节点的节点栏目
    if (pid <= 0) {
      pid = null;
      pc = new Channel();
      pc.setName(Channel.ROOT_NAME);
      pc.setId(Channel.ROOT_ID);
    } else {
      // pid >0 ,说明父栏目存在,查询出子栏目的父栏目信息
      pc = channelService.load(pid);
    }

    // 将子栏目的副栏目也传到页面
    model.addAttribute("pc", pc);
    model.addAttribute("channels", channelService.listByParent(pid));


    return "channel/list_child";
  }

  @RequestMapping("/channels")
  public String list(Model model) {
    return "channel/list";
  }

  @RequestMapping("/treeAll")
  public @ResponseBody
  List<ChannelTree> tree() {
    return channelService.generateTree();
  }

  // 用来异步记载树节点
  @RequestMapping(value = "/treeAys", method = RequestMethod.POST)
  public @ResponseBody
  List<TreeDto> tree(@RequestParam("pid") Integer pid) { // 接收?pid=xx
    List<TreeDto> tds = new ArrayList<>();
    if (null == pid) {
      tds.add(new TreeDto(Channel.ROOT_ID, Channel.ROOT_NAME, 1));
      return tds;
    }
    List<ChannelTree> cts = channelService.generateTreeByParent(pid);
    /* System.out.println(cts); */
    for (ChannelTree ct : cts) {
      // ct.getLeaf() 为0就是父节点，不为0就是子节点
      /* tds.add(new TreeDto(ct.getId(), ct.getName(), ct.getLeaf() == 0 ? 1 : 0)); */
    }
    return tds;
  }


  private void initAdd(Model model, Integer pid) {
    if (pid == null) pid = 0;
    Channel pc = null;
    if (pid == 0) {
      pc = new Channel();
      pc.setId(Channel.ROOT_ID);
      pc.setName(Channel.ROOT_NAME);
    } else {
      pc = channelService.load(pid);
    }
    model.addAttribute("pc", pc);
    model.addAttribute("types", EnumUtil.enumProp2NameMap(ChannelType.class, "name"));
    model.addAttribute(new Channel());
  }

  @RequestMapping(value = "/add/{pid}", method = RequestMethod.GET)
  public String add(@PathVariable Integer pid, Model model) {
    initAdd(model, pid);
    return "channel/add";
  }

  @RequestMapping(value = "/add/{pid}", method = RequestMethod.POST)
  public String add(@PathVariable Integer pid, Channel channel, BindingResult br, Model model) {
    if (br.hasErrors()) {
      initAdd(model, pid);
      return "channel/add";
    }
    channelService.add(channel, pid);
    return "redirect:/admin/channel/channels/" + pid+"?refresh=1";
  }

  @RequestMapping("/delete/{pid}/{id}")
  public String delte(@PathVariable Integer id, @PathVariable Integer pid, Model model) {
    channelService.delete(id);
    return "redirect:/admin/channel/channels/" + pid+"?refresh=1";

  }

  @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
  public String update(@PathVariable Integer id, Model model) {
    Channel c = channelService.load(id);
    model.addAttribute("channel", c);
    if (null == c.getParent()) {
      model.addAttribute("pc", new Channel(Channel.ROOT_ID, Channel.ROOT_NAME));
    } else {
      model.addAttribute("pc", c.getParent());
    }
    model.addAttribute("types", EnumUtil.enumProp2NameMap(ChannelType.class, "name"));

    return "channel/update";
  }

  @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
  public String update(@PathVariable Integer id, Channel channel, BindingResult br, Model model) {
    if (br.hasErrors()) {
      model.addAttribute("types", EnumUtil.enumProp2NameMap(ChannelType.class, "name"));
      return "channel/update";
    }
    int pid = 0;

    Channel tc = channelService.load(id);
    if (tc.getParent() != null) pid = tc.getParent().getId();
    tc.setCustomLink(channel.getCustomLink());
    tc.setCustomLinkUrl(channel.getCustomLinkUrl());
    tc.setIndex(channel.getIndex());
    tc.setTopNav(channel.getTopNav());
    tc.setName(channel.getName());
    tc.setRecommed(channel.getRecommed());
    tc.setType(channel.getType());
    tc.setStatus(channel.getStatus());
    channelService.update(tc);
    return "redirect:/admin/channel/channels/" + pid+"?refresh=1";
  }

  @RequestMapping("/channels/updateSort")
  public @ResponseBody
  AjaxObj updatSort(@RequestParam("ids") Integer[] ids) {
    try {
      channelService.updateSort(ids);
    } catch (Exception e) {
      return new AjaxObj(0, e.getMessage());
    }
    return new AjaxObj(1);
  }
}
